<?php
/**
 * URL管理类
 * false  ：默认模式，不对URL做任何处理。
 * path ：path模式。
 * @author andery <andery@foxmail.com>
 * @link http://www.minophp.com/
 * @version $Id: CUrlManager.php 2009-12-12 23:31:17Z andery $
 */
class CUrlManager {
    private static $_urlconf;//urlmanager配置信息
    private $_controller; //控制器
    private $_action; //方法
    private $_params = null; //URL参数数组
    private $_pathinfo; //应用程序所在目录名

    public function __construct(){
        $this->setPathInfo();
        $this->parseUrl();
    }
    
    public function getAppUrl()
    {
        $url = $this->getHostInfo().$this->getPath();
        $url = str_replace('\\', '', $url);
        return trim($url, '/');
    }
    
    /**
     * 获得当前URL
     * @return string
     */
    public function getUrl()
    {
        return $this->getHostInfo().$_SERVER['REQUEST_URI'];
    }
    
    /**
     * 获得URL的base部分
     * @return string
     */
    public function baseUrl()
    {
        if(strpos($this->getUrl(), $this->getBaseFile())) {
            $url = $this->getHostInfo().$_SERVER['SCRIPT_NAME'];
        } else {
            $url = $this->getHostInfo().$this->getPath();
        }
        $url = str_replace('\\', '', $url);
        return trim($url, '/');
    }
    
    /**
     * 获得当前的文件名
     * @return string
     */
    public function getBaseFile()
    {
        return $this->_pathinfo['basename'];
    }
    
    /**
     * 获得应用程序所在的目录
     * @return string
     */
    public function getPath()
    {
        return $this->_pathinfo['dirname'];
    }
    
    /**
     * 对SCRIPT_NAME进行解析
     * @return array
     */
    public function setPathInfo()
    {
        $this->_pathinfo = pathinfo($_SERVER['SCRIPT_NAME']);
    }
    
    public function removeUrlSuffix($pathInfo,$urlSuffix)
    {
        if ($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix) {
            return substr($pathInfo,0,-strlen($urlSuffix));
        } else {
            return $pathInfo;
        }			
    }
    
    /**
     * URL解析
     */
    public function parseUrl()
    {
    	$url = $this->getUrl();
        $request=trim(str_replace($this->baseUrl(), '', $url), '/');
        $url_model = CConf::get('urlmanager.url_model');
        // 通过URL传递参数noum=1避免重写
        if (isset($_GET['noum']) && $_GET['noum'] == '1') {
            $url_model = 'false';
        }
        
        //数据过滤
        if (!get_magic_quotes_gpc()) {
            Nimo::import('CString');
            isset($_POST) && $_POST = CString::saddslashes($_POST);
            isset($_GET) && $_GET = CString::saddslashes($_GET);
            isset($_COOKIE) && $_COOKIE   = CString::saddslashes($_COOKIE);
            isset($_REQUEST) && $_REQUEST  = CString::saddslashes($_REQUEST);
        }
        
        switch ($url_model) {
            case 'path' : 
                //规则部分
                $rules = CConf::get('urlmanager.rules');
                $depr = CConf::get('urlmanager.url_depr');
                $request = $this->removeUrlSuffix($request, CConf::get('urlmanager.url_suffix'));
                if($rules && is_array($rules)) {
                    foreach($rules as $key=>$value) {
                        $value = str_replace('/', $depr, $value);
                        $request = preg_replace('/'.$key.'/', $value, $request);
                    }
                }
                $splits = explode($depr, $request);
                $this->_controller = !empty($splits[0])?array_shift($splits):CConf::get('system.default_controller');
                $this->_action = !empty($splits[0])?array_shift($splits):CConf::get('system.default_action');
                $temkey = '';
                
                foreach($splits as $key=>$value) {
                    if($key%2==0){
                	    $temkey = $value;
                	    $_REQUEST[$temkey] = $_GET[$temkey] = $this->_params[$temkey] = '';
                    } else {
                        $_REQUEST[$temkey] = $_GET[$temkey] = $this->_params[$temkey] = $value;
                    }
                }
                unset($temkey);
                break;
            default :
                $this->_controller = !empty($_GET['m'])?$_GET['m']:CConf::get('system.default_controller');
                $this->_action = !empty($_GET['a'])?$_GET['a']:CConf::get('system.default_action');
                $this->_params = $_GET;
                break;
        }
    }
    
    /**
     * 生成模板需要的URL地址
     * 
     */
    public function create_url($route, $params=array())
    {
        $route=trim($route,'/');
        foreach ($params as &$param) {
            if($param===null) {
                $param='';
            }
        }
        $url = $this->baseUrl() . '/';
        $query = $m = $a = '';
        if (!$route&&!$params) {
            return $url;
        }
        $route_arr = explode('/', $route);
        if (isset($route_arr[0]) && $route_arr[0]!='') {
            $m = $route_arr[0];
        } else {
            $route_arr[0] = CConf::get('system.default_controller');
        }
        if (isset($route_arr[1]) && $route_arr[1]!='') {
            $a = $route_arr[1];
        } else {
            $route_arr[1] = CConf::get('system.default_action');
        }
        
        $url_model = CConf::get('urlmanager.url_model');
        // 通过URL传递参数noum=1避免重写
        if (isset($params['noum']) && $params['noum'] == '1') {
            $url_model = 'false';
        }
        //unset($params['noum']);
        switch ($url_model) {
            case 'path' :
                $creat_rules = CConf::get('urlmanager.creat_rules');
                $depr = CConf::get('urlmanager.url_depr');
                $suffix = CConf::get('urlmanager.url_suffix');
                
                $query .= implode($depr, $route_arr);
                foreach ($params as $key=>$val) {
                    if ($query!='') {
                        $query .= $depr;
                    }
                    $query .= $key . $depr . $val;
                }
                $query .= $suffix;
                if($creat_rules && is_array($creat_rules)) {
                    foreach ($creat_rules as $key=>$value) {
                        $key = str_replace('/', $depr, $key);
                        $query = preg_replace('/'.$key.'/', $value, $query);
                    }
                }
                break;
            default : 
                $m!='' ? $query .= '?m=' . $m : '';
                $a!='' ? $query .= '&a=' . $a : '';
                foreach ($params as $key=>$val) {
                    if ($query=='') {
                        $query .= '?' . $key . '=' . $val;
                    } else {
                        $query .= '&' . $key . '=' . $val;
                    }
                }
                break;
        }
        return $url .= $query;
    }
    
    /**
     * 获得域名信息
     * @return string
     */
    public function getHostInfo()
    {
        if(isset($_SERVER['HTTP_HOST']))
            $hostInfo='http://'.$_SERVER['HTTP_HOST'];
        else
        {
            $hostInfo='http://'.$_SERVER['SERVER_NAME'];
            $port=$_SERVER['SERVER_PORT'];
            if($port != 80 || $port != 443)
                $hostInfo.=':'.$port;
        }
        return $hostInfo;
    }
    
    /**
     * 获取当前控制器名称
     * @return string
     */
    public function getController()
    {
        return $this->_controller;
    }
    
    /**
     * 获取当前控制器需要调用的方法名
     * @return string
     */
    public function getAction()
    {
        return $this->_action;
    }
    
    public function getParams()
    {
        return $this->_params;
    }
}